import Recorder from "js-audio-recorder";
import { uploadFile } from "@/api/chat/im";

export default {
    data() {
        return {
            recorder: null,
            recordData: null,
        };
    },
    methods: {
        startRecord() {
            this.recorder = new Recorder({
                sampleBits: 16, // 采样位数
                sampleRate: 16000, // 采样率（兼容性最佳）
                numChannels: 1, // 声道数
            });
            this.recorder.start().then(() => {
                this.audioStatus = 1;
            });
        },
        stopRecord() {
            this.recorder.stop();
            this.audioStatus = 2;
            this.recordData = this.recorder.getWAVBlob();
        },
        playAudio() {
            if (this.audioStatus === 2) {
                this.recorder.play();
            }
        },
        deleteRecord() {
            this.recorder.destroy().then(function () {
                this.recorder = null;
            });
            this.audioStatus = 0;
            this.recordData = null;
        },
        handleAudioMsgSend() {
            // 上传音频文件
            const fileName = `voice-${Date.now()}.wav`;
            const file = new File([this.recordData], fileName, {
                type: "audio/wav",
            });
            uploadFile(file, { fileName: fileName }).then(res => {
                console.log(res);
                this.sendAudioMsg(res.fileUrl);
                this.deleteRecord();
            });
        },
    },
};
